import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-factor',
  templateUrl: './factor.component.html'
})
export class FactorComponent implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = ''
  deviceId: string = ''
  carNumber: string = ''
  dateType: string = 'startTime'
  sensorStatus: string | number = '' //传感器状态，0无损坏，1有损坏
  lineStatus: string | number = '' //线材状态，0无损坏，1有损坏
  selectedCompanyId: string = ''
  selectedCompanyName: string = ''
  startTime: string = '' //table时间控件
  endTime: string = '' //table时间控件
  startTime_chart: string = '' //ehart折线图时间控件
  endTime_chart: string = '' //ehart折线图时间控件
  selectedRow: any //选中的row数据
  isChartView = false
  isMapView = false
  drawTrackArr: any //画轨迹的数据
  specifyId = {
    picker1: 'datetimepicker3',
    picker2: 'datetimepicker4'
  }

  initSelectDay = 3 // 时间选择框默认查询时间跨度（day）

  specifyTime = {
    startTime: '',
    endTime: ''
  }
  sensorStatusEnum = ['正常', '正负52万', '乱跳', '形变小', '平直', '未安装', '甩挂'] //0：正常，1：正负52万，2：乱跳  3形变小  4平直  5未安装 6甩挂
  activeSelected: string = '' //当前选择的row数据
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }

  //折线图时间回调事件
  getSelectChartTime(time) {
    this.startTime_chart = time.startTime
    this.endTime_chart = time.endTime
  }
  //时间change回调
  getSelectTableTime(val) {
    this.startTime = val.startTime
    this.endTime = val.endTime
    // 初始化时间后会触发这个回调，所以在这里调用 load 方法
    this.load()
  }
  ngOnInit() {
    // this.load()
  }
  runParent(value) {
    this.drawTrackArr = value
  }
  showMapView(val) {
    this.isMapView = val
  }
  // 关闭图标
  closeChart(): void {
    this.isChartView = false
  }
  //数据查看
  drawAbnormalChart() {
    if (!this.selectedRow) {
      this.jsonApiService.message('先选择需要查看折线图的车辆')
      return
    }
    if (!this.startTime_chart || !this.endTime_chart) {
      this.jsonApiService.message('时间不能为空')
      return
    }
    let timeCheck = common.correctTimeParams(this.startTime_chart, this.endTime_chart, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let params = {
      deviceId: this.selectedRow.deviceId,
      startTime: this.startTime_chart,
      endTime: this.endTime_chart,
      coefficient: this.selectedRow.currentCoef
    }
    this.selectedRow = params
  }
  checkAbnormal(row) {
    this.activeSelected = row.id
    this.startTime_chart = row.startTime
    this.endTime_chart = row.endTime
    this.isChartView = true
    row.coefficient = row.currentCoef
    this.specifyTime = {
      startTime: this.startTime_chart,
      endTime: this.endTime_chart
    }
    this.selectedRow = row
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据
  load() {
    let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    const sensorStatusEnum = this.sensorStatusEnum
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        dateType: this.dateType,
        startTime: this.startTime,
        endTime: this.endTime,
        sensorStatus: this.sensorStatus, //新增传感器状态参数
        lineStatus: this.lineStatus,
        searchKey: common.stringTrim(this.searchKey)
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('sensormonitor/sensorCoefForPage.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
        for (let item of data.exhibitDatas) {
          if (item.sensorStatus) {
            item.sensorDamageDetail = item.sensorStatus.reduce((acc, current, index) => {
              if (current === 1 || current === 2 || current === 3 || current === 4) {
                if (acc) {
                  acc = acc + '，'
                }
                acc = acc + `传感器${index + 1}-${sensorStatusEnum[current]}`
              }
              return acc
            }, '')
          }
          if (item.coef) {
            let coefArr = []
            for (let i = 0; i < item.coef.length; i++) {
              let _item = item.coef[i]
              if (_item) {
                let obj: any = {
                  value: _item,
                  index: i + 1
                }
                coefArr.push(obj)
              }
            }
            item.coefT = coefArr
          } else {
            item.coefT = []
          }
          if (item.currentCoef) {
            let currentCoef = []
            for (let i = 0; i < item.currentCoef.length; i++) {
              let _item = item.currentCoef[i]
              if (_item) {
                let obj: any = {
                  value: item.currentCoef[i],
                  index: i + 1
                }
                currentCoef.push(obj)
              }
            }
            item.currentCoefT = currentCoef
          } else {
            item.currentCoefT = []
          }
        }
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //合同删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('sensormonitor/deleteForSensorCoef.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //公司选中回调
  companySelected(data) {
    this.selectedCompanyId = data.companyId
    this.selectedCompanyName = data.companyName
    this.deviceId = data.deviceId
    this.carNumber = data.carNumber
  }
  // 数据导出
  exportData() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        dateType: this.dateType,
        startTime: this.startTime,
        endTime: this.endTime,
        sensorStatus: this.sensorStatus, //新增传感器状态参数
        lineStatus: this.lineStatus,
        searchKey: common.stringTrim(this.searchKey),
        export: '1'
      }
    }
    let timeCheck = common.correctTime(data.parameters, ['dateType', 'export'])
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'sensormonitor/sensorCoefForPage.html')
  }
}
